package com.myschool.server.manager.impl;

import org.myschool.common.exception.ApplicationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.myschool.server.dao.SchoolDao;
import com.myschool.server.dao.UserDao;
import com.myschool.server.dao.support.BaseEntityDaoHibernate;
import com.myschool.server.manager.BaseManager;
import com.myschool.server.manager.SchoolManager;
import com.myschool.server.model.School;
import com.myschool.server.model.User;

@Service
@Transactional
public class SchoolManagerImpl extends BaseManager<School> implements
		SchoolManager {

	@Autowired
	private SchoolDao dao;

	@Autowired
	private UserDao userDao;

	@Override
	protected BaseEntityDaoHibernate getDao() {
		return (BaseEntityDaoHibernate) this.dao;
	}

	@Transactional(readOnly = false, rollbackFor = ApplicationException.class)
	public User registerSchool(School school, User user)
			throws ApplicationException {
		try {
			this.dao.save(school);

			if (user.getEntityId() != null) {
				user = this.userDao.retrieveUser(user);

			}
			user.setSchool(school);
			this.userDao.save(user);

			return user;
		} catch (Exception exp) {
			throw new ApplicationException(exp, "error during registration");
		}

	}

}
